API Specification

AquaX — Backend API Current-Code Baseline

Document Info
Version 1.0
Status Draft — Current Backend API Baseline
Created Date 2026-09-17
Last Updated 2026-09-17
Owner Backend & API
Reviewers Web, Mobile, QA, Security
Source Code Reviewed backend/main.ts, backend/app.module.ts, backend/modules/**/**.controller.ts, backend/common/dtos/*, web/src/core/constants/api-url.ts, mobile/src/core/constants/apiURL.constants.ts

Implementation alignment note: This document is generated from the current backend controller code and the current web/mobile API constants. It describes the API surface that exists now. Permission enforcement status is called out separately because several service/use-case checks still contain TEMPORARY BYPASS comments.


Table of Contents

  1. Executive Summary
  2. API Runtime Baseline
  3. Authentication And Session Model
  4. Response And Error Conventions
  5. Pagination, Filtering And Validation
  6. Security And Permission Review
  7. API Inventory By Module
  8. Web And Mobile Client Mapping
  9. Planned Or Stubbed API Areas
  10. API Testing Checklist
  11. Open Issues And Required Follow-Up
  12. Traceability
  13. Document History

1. Executive Summary

AquaX backend is a NestJS API exposed under the global prefix:

/api

Swagger is configured at:

/api/docs

The current API covers:

  • authentication and session management;
  • users, scopes, farms, ponds and crops;
  • sensors, parameter thresholds, water timeseries and dashboards;
  • alerts, tickets, notifications and activity logs;
  • feeding, farming logs, todo tasks and reports;
  • devices, auto-rules and IoT ingest/control;
  • handbook articles and locations;
  • settings and owner dashboard APIs.

Current implementation status:

Area Status Notes
API routing CONFIRMED Controllers and frontend/mobile constants exist for current core modules.
Swagger CONFIRMED Generated from Nest Swagger at /api/docs.
JWT auth CONFIRMED Access token bearer auth is used for protected API routes.
Refresh session CONFIRMED Web uses httpOnly cookie; mobile sends refresh token in body/header with x-client-type: mobile.
Role enforcement PARTIAL Some controllers use @Roles(...); many protected controllers rely on scope logic or have no method-level role metadata.
Scope enforcement PARTIAL Several farm/pond/crop/device/log checks contain TEMPORARY BYPASS.
AI APIs PLANNED No production chatbot/recommendation/prediction API is implemented.

2. API Runtime Baseline

2.1 Server Configuration

Item Current Code
Framework NestJS
Global prefix /api
Default port 3001 if PORT is not set
Swagger path /api/docs
CORS origins CORS_ORIGINS env or localhost defaults 3000, 5173, 5174
CORS credentials Enabled
Allowed methods GET, POST, PUT, PATCH, DELETE
Allowed headers Content-Type, Authorization, x-client-type, x-refresh-token
Validation Global ValidationPipe with whitelist, forbidNonWhitelisted, transform
Rate limiting Global throttler: 100 requests / minute / IP; login overrides to 10 / minute
API logging Successful /api requests are logged, except Swagger assets

2.2 Base URLs

Consumer Base URL Behavior
Backend runtime Routes are available under /api/....
Web client httpClient.baseURL = env.apiBaseUrl; endpoint constants omit /api.
Mobile client apiClient.baseURL = env.apiUrl; endpoint constants omit /api.

Example:

GET /api/auth/profile

Client constant:

API_URL.AUTH.PROFILE = "/auth/profile"

3. Authentication And Session Model

3.1 Auth Mechanisms

Mechanism Header / Cookie Used By Notes
Access token Authorization: Bearer <accessToken> Web, mobile, protected APIs Validated by JwtAuthGuard; request receives req.user.
Refresh cookie refreshToken httpOnly cookie Web Set by login/refresh; used by /auth/refresh.
Mobile refresh token Body refreshToken or header x-refresh-token Mobile Login/refresh returns refresh token in JSON when x-client-type: mobile.
IoT ingest token Authorization: Bearer <IOT_INGEST_TOKEN> MQTT/IoT worker Used by /iot/v1/telemetry and /iot/v1/commands/:commandId/ack.

3.2 Auth Routes

Method Path Auth Purpose
POST /api/auth/login Public Login by email/password, returns access token and session user; sets refresh cookie.
POST /api/auth/logout JWT Revoke current session or all devices.
POST /api/auth/refresh Refresh token Refresh access token; cookie for web, body/header for mobile.
POST /api/auth/forgot-password Public Request password reset.
POST /api/auth/reset-password Public Reset password with token.
GET /api/auth/profile JWT Current user profile, roles and scope.
POST /api/auth/change-password JWT Change password for current user.
GET /api/auth/sessions JWT List current user's sessions.
POST /api/auth/sessions/:sessionId/revoke JWT Revoke a specific session.

3.3 Auth Payload Notes

Login input:

{
  "email": "[email protected]",
  "password": "Owner@2026"
}

Mobile clients should send:

x-client-type: mobile

Mobile refresh requests currently send:

x-client-type: mobile
x-refresh-token: <refreshToken>

and body:

{
  "refreshToken": "<refreshToken>"
}

4. Response And Error Conventions

4.1 Standard Item Response

Most item endpoints return:

{
  "data": {},
  "message": "Thành công"
}

Implemented by:

ResponseItem<T>
SimpleResponse<T>

4.2 Paginated Response

Paginated endpoints return:

{
  "data": [],
  "meta": {
    "page": 1,
    "take": 10,
    "itemCount": 0,
    "pageCount": 0,
    "hasPreviousPage": false,
    "hasNextPage": false
  },
  "message": "Thành công"
}

Implemented by:

ResponsePaginate<T>
PageMetaDto

4.3 Common Error Behavior

Current global validation:

  • unknown body fields are rejected;
  • DTO validation errors return 400;
  • missing/invalid JWT returns 401;
  • role mismatch where enforced returns 403;
  • Prisma exceptions are handled by PrismaExceptionFilter.

Typical frontend error handling extracts:

response.data.message

If message is an array, the web client uses the first item.


5. Pagination, Filtering And Validation

5.1 Standard Pagination Query

Common paginated DTO fields:

Query Type Default Notes
search string "" Keyword search.
order enum DESC Sort order.
orderBy string createdAt Sort field.
page integer 1 Minimum 1.
take integer 10 Minimum 1, maximum 100.

5.2 Common Filters

Filters vary by module. Current clients use common filters such as:

  • farmId;
  • pondId;
  • cropId;
  • status;
  • severity;
  • role;
  • isActive;
  • from, to;
  • dashboard timePreset;
  • report/export type and time range.

6. Security And Permission Review

6.1 Confirmed Guards

Guard Purpose
JwtAuthGuard Validates bearer access token, active session and active user.
RolesGuard Enforces @Roles(...) metadata when present. If no role metadata is present, it allows the request.
IotIngestTokenGuard Validates ingest bearer token against IOT_INGEST_TOKEN.
ThrottlerGuard Global rate limiting.

6.2 Explicit Role-Guarded Areas

Area Current Role Decorator
Owner dashboard @Roles(Role.OWNER)
Activity logs list @Roles(Role.ADMIN, Role.OWNER)
Activity logs export @Roles(Role.ADMIN)
Settings incident response @Roles(Role.ADMIN)

6.3 Important Code Review Findings

Severity Finding Evidence Risk Required Action
Critical Admin-only user APIs are not actually blocked by AdminGuard; it always returns true. backend/modules/users/guards/admin.guard.ts:15-19 Non-admin users may reach user-management behavior if this guard is used as the final authorization control. Restore ForbiddenException, add tests for non-admin access.
High Several controllers use RolesGuard but most methods do not declare @Roles(...). users.controller.ts:75-76, farms.controller.ts:50-51, ponds.controller.ts:56-57 Role enforcement may be weaker than readers expect from RolesGuard presence. Add explicit @Roles or document service-level scope checks per endpoint.
High Farm, pond, crop, sensor, device and farming-log use cases contain TEMPORARY BYPASS comments around authorization and edit-lock rules. Examples: farms.controller.ts:82-83, devices/create-device.use-case.ts:15-16, sensors/create-sensor.use-case.ts:12-13, crops/create-crop.use-case.ts:25-27, farming-logs/update-manual-water.use-case.ts:28-29 Cross-scope access, unauthorized device/sensor changes, and historical record edits can slip through. Remove bypasses before production and add regression tests.
Medium Legacy viewer aliases still exist for owner APIs. Dashboard and farm endpoints expose both owner and viewer paths. Naming confusion after mobile role enum was aligned to OWNER. Keep aliases for compatibility; migrate client/API naming to owner consistently later.
Medium Some admin operations are documented in summaries as admin-only but lack method-level @Roles(Role.ADMIN). Handbook admin actions, notification config, sensors/devices create/update/delete. Swagger/spec may imply stronger restrictions than code enforces. Add role decorators or document exact authorization location.

7. API Inventory By Module

All paths below are shown with the /api prefix.

Legend:

Auth Meaning
Public No JWT required.
JWT Requires bearer access token.
Role Requires JWT and explicit @Roles.
IoT Token Requires IOT_INGEST_TOKEN bearer token.
Partial Guard exists but role/scope enforcement should be reviewed due bypasses or missing role metadata.

7.1 Health And Locations

Method Path Auth Purpose
GET /api/health Public Health check.
GET /api/status.json Public Status JSON.
GET /api/locations/provinces Public List provinces/cities.
GET /api/locations/wards Public List wards by province/city.

7.2 Users And Scope

Method Path Auth Purpose
POST /api/users JWT / Partial Create user.
GET /api/users/summary JWT / Partial User-management summary.
GET /api/users JWT / Partial List users.
GET /api/users/audit-logs JWT / Partial User audit logs.
POST /api/users/scope/assign JWT / Partial Assign farm scope.
PUT /api/users/scope/replace-owner JWT / Partial Replace farm owner.
DELETE /api/users/scope/remove JWT / Partial Remove farm scope.
POST /api/users/ktv JWT / Partial Create KTV user.
GET /api/users/scope/farm/:farmId/members JWT / Partial List farm members.
PUT /api/users/technician-assignments/sync JWT / Partial Sync technician assignments.
GET /api/users/:id JWT / Partial User detail.
GET /api/users/:id/constraints JWT / Partial User delete/role-change constraints.
PUT /api/users/:id/status JWT / Partial Enable/disable user.
PUT /api/users/:id JWT / Partial Update user.
DELETE /api/users/:id JWT / Partial Delete/deactivate user.

7.3 Farms

Method Path Auth Purpose
POST /api/farms JWT / Partial Create farm.
GET /api/farms JWT / Partial List farms.
GET /api/farms/management JWT / Partial Farm management list.
GET /api/farms/owner/home JWT / Partial Owner mobile home data.
GET /api/farms/viewer/home JWT / Partial Legacy alias for owner home.
GET /api/farms/technician/home JWT / Partial Technician home data.
GET /api/farms/owner/list JWT / Partial Owner farm list.
GET /api/farms/viewer/list JWT / Partial Legacy alias for owner farm list.
GET /api/farms/owner/:id/detail JWT / Partial Owner farm detail.
GET /api/farms/viewer/:id/detail JWT / Partial Legacy alias for owner farm detail.
GET /api/farms/:id JWT / Partial Farm detail.
PUT /api/farms/:id JWT / Partial Update farm.
DELETE /api/farms/:id JWT / Partial Delete/soft-delete farm.
GET /api/farms/:id/delete-info JWT / Partial Farm delete impact information.
GET /api/farms/:id/dashboard JWT / Partial Farm dashboard.

7.4 Ponds

Method Path Auth Purpose
POST /api/ponds JWT / Partial Create pond.
GET /api/ponds JWT / Partial List ponds.
GET /api/ponds/management JWT / Partial Pond management list.
GET /api/ponds/:id JWT / Partial Pond detail.
PUT /api/ponds/:id JWT / Partial Update pond.
DELETE /api/ponds/:id JWT / Partial Delete pond.
POST /api/ponds/:id/assign JWT / Partial Assign users to pond.
POST /api/ponds/:id/reassign-technician JWT / Partial Reassign pond technician.
DELETE /api/ponds/:id/assign/:userId JWT / Partial Remove assigned user from pond.
GET /api/ponds/:id/assignments JWT / Partial List pond assignments.
GET /api/ponds/:id/water-timeseries JWT / Partial Pond water metric time series.
GET /api/ponds/:id/devices-tab JWT / Partial Pond devices tab.
GET /api/ponds/:id/feeding-tab JWT / Partial Pond feeding tab.
GET /api/ponds/:id/logs-tab JWT / Partial Pond logs tab.
GET /api/ponds/:id/warnings-tab JWT / Partial Pond warnings tab.
GET /api/ponds/:id/reports-tab JWT / Partial Pond reports tab.
GET /api/ponds/:id/dashboard JWT / Partial Pond dashboard.

7.5 Crops

Method Path Auth Purpose
POST /api/crops JWT / Partial Create crop.
GET /api/crops JWT / Partial List crops by pond.
GET /api/crops/species JWT List crop species catalog.
POST /api/crops/species JWT / Partial Create crop species catalog item.
GET /api/crops/size-ranges JWT List crop size ranges.
POST /api/crops/size-ranges JWT / Partial Create crop size range item.
GET /api/crops/:id JWT / Partial Crop detail.
PUT /api/crops/:id JWT / Partial Update crop.
DELETE /api/crops/:id JWT / Partial Delete crop.
POST /api/crops/:id/close JWT / Partial Close crop.
POST /api/crops/:id/override JWT / Partial Override crop dates/status.
GET /api/crops/active/:pondId JWT / Partial Active crop for pond.

7.6 Sensors And Thresholds

Method Path Auth Purpose
POST /api/sensors JWT / Partial Create sensor.
GET /api/sensors JWT List sensors.
GET /api/sensors/pond/:pondId JWT List sensors by pond.
GET /api/sensors/:id JWT Sensor detail.
PUT /api/sensors/:id JWT / Partial Update sensor.
DELETE /api/sensors/:id JWT / Partial Delete sensor.
POST /api/sensors/:id/readings JWT Create sensor reading.
GET /api/sensors/:id/readings JWT List sensor readings.
GET /api/sensors/:id/readings/chart JWT Sensor chart readings.
GET /api/parameter-thresholds JWT List parameter thresholds.
PUT /api/parameter-thresholds/:id JWT Update threshold.
PUT /api/parameter-thresholds/bulk/:pondId JWT Bulk update pond thresholds.
DELETE /api/parameter-thresholds/:id JWT Delete threshold.

7.7 Alerts

Method Path Auth Purpose
GET /api/alerts JWT List alerts with filters/stats.
GET /api/alerts/:id JWT Alert detail with status history.
POST /api/alerts/:id/acknowledge JWT Acknowledge alert.
POST /api/alerts/:id/start-processing JWT Start alert processing.
POST /api/alerts/:id/close JWT Close alert.
POST /api/alerts/:id/reopen JWT Reopen alert.
POST /api/alerts/:id/assign JWT Assign alert.
PATCH /api/alerts/:id/mark-read JWT Mark alert read.
POST /api/alerts/bulk-mark-read JWT Mark multiple alerts read.

7.8 Devices And IoT

Method Path Auth Purpose
GET /api/devices JWT List devices.
GET /api/devices/stats JWT Device stats summary.
GET /api/devices/:id JWT Device detail.
POST /api/devices JWT / Partial Create device.
PATCH /api/devices/:id JWT / Partial Update device.
DELETE /api/devices/:id JWT / Partial Delete device.
POST /api/devices/:id/commands JWT Send command to device.
GET /api/devices/:id/commands JWT Device command history.
PATCH /api/devices/:id/commands/:cmdId JWT Update command execution status.
GET /api/devices/auto-rules JWT List auto-rules.
POST /api/devices/auto-rules JWT Create auto-rule.
PATCH /api/devices/auto-rules/:id JWT Update auto-rule.
DELETE /api/devices/auto-rules/:id JWT Delete auto-rule.
POST /api/iot/v1/telemetry IoT Token Ingest telemetry from MQTT worker.
POST /api/iot/v1/commands/:commandId/ack IoT Token Ingest command ACK.
GET /api/iot/v1/device-registrations JWT List device registrations.
GET /api/iot/v1/device-registrations/:id JWT Device registration detail.
POST /api/iot/v1/device-registrations/:id/map JWT Map/update device registration.
POST /api/iot/v1/device-registrations/:id/assign JWT Assign device registration.
PATCH /api/iot/v1/device-registrations/:id/disable JWT Disable device registration.
PATCH /api/iot/v1/device-registrations/:id/enable JWT Enable device registration.
POST /api/iot/v1/device-registrations/:id/controls JWT Publish direct local output command.
PATCH /api/iot/v1/device-registrations/:id/controls/mode JWT Set fixed IoT output mode.

7.9 Feeding And Farming Logs

Method Path Auth Purpose
GET /api/feeding-records/feed-types JWT List feed types.
POST /api/feeding-records/feed-types JWT Create feed type.
POST /api/feeding-records JWT Create feeding record.
GET /api/feeding-records JWT List feeding records.
GET /api/feeding-records/suggest JWT Feeding suggestion contract; currently planned/stubbed.
GET /api/feeding-records/pcr-fcr JWT PCR/FCR metrics; formula-dependent/stubbed.
GET /api/feeding-records/:id JWT Feeding record detail.
PATCH /api/feeding-records/:id JWT Update feeding record.
DELETE /api/feeding-records/:id JWT Delete feeding record.
POST /api/farming-logs/water JWT Create manual water record.
GET /api/farming-logs/water JWT List manual water records.
GET /api/farming-logs/water/:id JWT Manual water detail.
PATCH /api/farming-logs/water/:id JWT / Partial Update manual water record.
DELETE /api/farming-logs/water/:id JWT / Partial Delete manual water record.
POST /api/farming-logs/minerals JWT Create mineral record.
GET /api/farming-logs/minerals JWT List mineral records.
GET /api/farming-logs/minerals/:id JWT Mineral detail.
PATCH /api/farming-logs/minerals/:id JWT / Partial Update mineral record.
DELETE /api/farming-logs/minerals/:id JWT / Partial Delete mineral record.
POST /api/farming-logs/siphons JWT Create siphon record.
GET /api/farming-logs/siphons JWT List siphon records.
GET /api/farming-logs/siphons/:id JWT Siphon detail.
PATCH /api/farming-logs/siphons/:id JWT / Partial Update siphon record.
DELETE /api/farming-logs/siphons/:id JWT / Partial Delete siphon record.
POST /api/farming-logs/productivity JWT Create productivity record.
GET /api/farming-logs/productivity JWT List productivity records.
GET /api/farming-logs/productivity/summary JWT Productivity summary.
GET /api/farming-logs/productivity/:id JWT Productivity detail.
PATCH /api/farming-logs/productivity/:id JWT / Partial Update productivity record.
DELETE /api/farming-logs/productivity/:id JWT / Partial Delete productivity record.
GET /api/farming-logs/log JWT Unified farming log feed.
POST /api/farming-logs/:recordType/:recordId/attachments JWT Upload farming-log attachment.
DELETE /api/farming-logs/attachments/:attachmentId JWT Delete farming-log attachment.

7.10 Tickets

Method Path Auth Purpose
POST /api/tickets JWT Create ticket.
GET /api/tickets JWT List tickets with filters.
GET /api/tickets/stats JWT Ticket statistics.
GET /api/tickets/:id JWT Ticket detail with history/attachments.
POST /api/tickets/:id/assign JWT Assign ticket.
POST /api/tickets/:id/acknowledge JWT Acknowledge ticket.
POST /api/tickets/:id/start-processing JWT Start ticket processing.
POST /api/tickets/:id/close JWT Close ticket.
DELETE /api/tickets/:id JWT Delete ticket.
POST /api/tickets/:id/attachments JWT Upload ticket attachment.
DELETE /api/tickets/:id/attachments/:attachmentId JWT Delete ticket attachment.
GET /api/tickets/:id/attachments/:attachmentId/download JWT Download ticket attachment.
GET /api/tickets/:id/comments JWT List ticket comments.
POST /api/tickets/:id/comments JWT Add ticket comment.

7.11 Notifications And Activity Logs

Method Path Auth Purpose
GET /api/notifications JWT List notifications.
GET /api/notifications/stats JWT Notification totals/unread stats.
GET /api/notifications/stream JWT Server-sent notification events.
PATCH /api/notifications/:id/read JWT Mark notification read.
POST /api/notifications/mark-all-read JWT Mark all notifications read.
POST /api/notifications/device-tokens JWT Register push token.
POST /api/notifications/device-tokens/unregister JWT Unregister push token.
DELETE /api/notifications/:id JWT Delete notification.
GET /api/notifications/config JWT / Partial List notification configs.
POST /api/notifications/config JWT / Partial Create notification config.
PUT /api/notifications/config/:id JWT / Partial Update notification config.
DELETE /api/notifications/config/:id JWT / Partial Delete notification config.
GET /api/activity-logs Role: ADMIN, OWNER List unified pond activity logs.
GET /api/activity-logs/export Role: ADMIN Export activity logs to Excel.

7.12 Reports

Method Path Auth Purpose
GET /api/reports/overview JWT Report overview.
GET /api/reports/water-monitoring JWT Water monitoring report.
GET /api/reports/devices JWT Device report.
GET /api/reports/feeding JWT Feeding report.
GET /api/reports/manual-environment JWT Manual environment report.
GET /api/reports/recent JWT Recent report history.
POST /api/reports/excel JWT Start Excel export job.
GET /api/reports/excel/:jobId JWT Poll Excel export status/download URL.

7.13 Dashboard

Owner dashboard endpoints have explicit @Roles(Role.OWNER).

Method Path Auth Purpose
GET /api/dashboard/owner Role: OWNER Owner dashboard aggregate.
GET /api/dashboard/viewer Role: OWNER Legacy alias.
GET /api/dashboard/owner/filters Role: OWNER Dashboard filters.
GET /api/dashboard/owner/summary Role: OWNER Summary metrics.
GET /api/dashboard/owner/farm-health Role: OWNER Farm health.
GET /api/dashboard/owner/ponds Role: OWNER Pond list.
GET /api/dashboard/owner/ponds-to-handle Role: OWNER Ponds needing action.
GET /api/dashboard/owner/alerts Role: OWNER Dashboard alerts.
GET /api/dashboard/owner/devices Role: OWNER Dashboard devices.
GET /api/dashboard/owner/activities Role: OWNER Recent activities.
GET /api/dashboard/owner/farms/:id Role: OWNER Farm drawer detail.
GET /api/dashboard/owner/ponds/:id Role: OWNER Pond drawer detail.
GET /api/dashboard/owner/devices/:id Role: OWNER Device drawer detail.
GET /api/dashboard/owner/alerts/:id Role: OWNER Alert drawer detail.

The same endpoints also currently expose viewer/... aliases.

7.14 Handbook

Method Path Auth Purpose
GET /api/handbook JWT List articles.
GET /api/handbook/bookmarked JWT User bookmarks.
GET /api/handbook/by-alert JWT Alert-related articles.
GET /api/handbook/:id JWT Article detail.
GET /api/handbook/:id/versions JWT Article version metadata.
GET /api/handbook/:id/versions/:versionNumber JWT Version content.
POST /api/handbook/:id/bookmark JWT Toggle bookmark.
POST /api/handbook JWT / Partial Create article; summary says admin only.
PATCH /api/handbook/:id JWT / Partial Update article; summary says admin only.
POST /api/handbook/:id/submit JWT / Partial Submit article for approval.
POST /api/handbook/:id/approve JWT / Partial Approve article.
POST /api/handbook/:id/reject JWT / Partial Reject article.
POST /api/handbook/:id/archive JWT / Partial Archive article.
POST /api/handbook/:id/restore JWT / Partial Restore article.

7.15 Settings And Todo Tasks

Method Path Auth Purpose
GET /api/settings/incident-response Role: ADMIN Get incident response settings.
PUT /api/settings/incident-response Role: ADMIN Update incident response settings.
GET /api/todo-tasks/home JWT Owner home todo summary.
GET /api/todo-tasks JWT List owner todo tasks.
POST /api/todo-tasks JWT Create owner todo task.
GET /api/todo-tasks/:id JWT Todo detail.
PATCH /api/todo-tasks/:id JWT Update todo.
DELETE /api/todo-tasks/:id JWT Delete todo.
POST /api/todo-tasks/:id/toggle-complete JWT Toggle completion.

8. Web And Mobile Client Mapping

8.1 Web Constants

Web API constants currently cover:

  • auth;
  • users;
  • farms;
  • locations;
  • ponds;
  • crops;
  • reports;
  • notifications;
  • devices and auto-rules;
  • parameter thresholds;
  • IoT device registrations;
  • tickets;
  • activity logs;
  • settings;
  • owner dashboard.

Source:

web/src/core/constants/api-url.ts

8.2 Mobile Constants

Mobile API constants currently cover:

  • auth/profile/change password;
  • users;
  • farms;
  • owner legacy viewer farm/home endpoints;
  • technician home;
  • ponds tabs/dashboard;
  • devices auto-rules and IoT output controls;
  • crops/catalog/close/detail;
  • feeding/feed types;
  • farming logs and attachments;
  • tickets/stats/detail;
  • notifications/device tokens;
  • todo tasks.

Source:

mobile/src/core/constants/apiURL.constants.ts

8.3 Client Naming Notes

Topic Current State
/api prefix Not included in constants; configured through base URL.
Owner/viewer naming Backend supports both owner and legacy viewer paths for several owner APIs. Mobile still uses some VIEWER_* constant names for those paths, but auth role value is now OWNER.
Web owner dashboard Uses /dashboard/owner/* paths.
Mobile owner farm/home Uses /farms/viewer/* legacy alias paths.

9. Planned Or Stubbed API Areas

Area Current API State Product State
AI chatbot No production chatbot API found. Planned MVP 3.
AI image analysis No production image-analysis API found. Planned MVP 4.
AI prediction No production prediction API found. Planned MVP 3-4.
AI feeding suggestion /feeding-records/suggest exists as contract endpoint, but PRD/SRS mark recommendation as planned/stubbed. Planned MVP 4.
PCR/FCR /feeding-records/pcr-fcr exists, formula-dependent/stubbed. Planned/pending formula.
Scheduled weekly reports Manual/on-demand report/export APIs exist; scheduled weekly email reports are planned. Planned.
SMS/Zalo/calls No current API. Future.

10. API Testing Checklist

Minimum regression checklist:

ID Test Area Expected Result
API-TC-001 Public health and location endpoints. Accessible without JWT.
API-TC-002 Protected endpoint without token. Returns 401.
API-TC-003 Expired/invalid access token. Returns 401; client attempts refresh where applicable.
API-TC-004 Web refresh cookie flow. /auth/refresh returns new access token using cookie.
API-TC-005 Mobile refresh body/header flow. /auth/refresh returns new access and refresh token with x-client-type: mobile.
API-TC-006 Owner requests another owner's farm/pond. Denied after scope hardening.
API-TC-007 Technician requests unassigned pond/ticket. Denied after scope hardening.
API-TC-008 Non-admin calls user/device/sensor admin mutation. Denied after role hardening.
API-TC-009 IoT ingest without ingest token. Returns 401.
API-TC-010 Report/export scope. Export contains only authorized data.
API-TC-011 Ticket attachment upload/download. Requires auth and scoped ticket access.
API-TC-012 Notification target links. User can open only authorized targets.
API-TC-013 Farming log past-date edits. Blocked once bypasses are removed and finalization rule is active.

11. Open Issues And Required Follow-Up

ID Issue Owner Priority
API-OI-001 Remove TEMPORARY BYPASS authorization/edit-lock comments and enforce intended exceptions. Backend/Security P0
API-OI-002 Add explicit @Roles(...) to admin-only and role-specific mutation endpoints, or document service-level checks. Backend/Security P0
API-OI-003 Add negative permission tests for owner/manager/technician/admin boundaries. QA/Backend P0
API-OI-004 Decide migration plan for legacy viewer route aliases. Product/Backend/Mobile P2
API-OI-005 Document detailed DTO schemas from Swagger export or generate OpenAPI artifact in CI. Backend P1
API-OI-006 Confirm production API base URL, CORS origins and cookie domain/SameSite policy. DevOps/Security P1
API-OI-007 Define file upload limits, media retention and signed-download behavior. Backend/Security P1
API-OI-008 Define AI API contract before MVP 3 implementation. Product/AI/Backend P1

12. Traceability

Area Source
Runtime and Swagger backend/main.ts
Module list backend/app.module.ts
Response DTOs backend/common/dtos/*
Auth/session backend/modules/auth/**
Controllers backend/modules/**/**.controller.ts
IoT ingest token backend/modules/iot-ingest/guards/iot-ingest-token.guard.ts
Web API constants web/src/core/constants/api-url.ts
Mobile API constants mobile/src/core/constants/apiURL.constants.ts
Permission baseline 05_Permission Matrix.md
Product backlog 06_User Stories — Product Backlog.md
API-related requirements 03_SRS — Software Requirements Specification.md

13. Document History

Version Date Author Changes
1.0 2026-09-17 Backend & API Created API specification from current backend controllers, auth/runtime code and web/mobile API constants.

End of API Specification